from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.template import loader
from django.urls import reverse
from .models import Topic, Entry
# Create your views here.
def index(request):
    template = loader.get_template('learning_logs/index.html')
    return HttpResponse(template.render({}, request))

def topics(request):
    topics = Topic.objects.all()
    template = loader.get_template('learning_logs/topics.html')
    context = {
        'topics': topics,
    }
    return HttpResponse(template.render(context, request))

def topic(request, topic_id):
    try:
        topic = Topic.objects.get(pk=topic_id)
        template = loader.get_template('learning_logs/topic.html')
        entry_list = topic.entry_set.order_by('-date_added')
    except Topic.DoesNotExist:
        raise Http404("topic does not exist")
    return HttpResponse(template.render({'topic': topic, 'entry_list': entry_list}, request))

def new_topic(request):
    if request.method == 'GET':
        template = loader.get_template('learning_logs/new_topic.html')
        return HttpResponse(template.render({}, request))
    elif request.method == 'POST':
        topic_text = request.POST['text']
        topic = Topic()
        topic.text = topic_text
        topic.save()
        return HttpResponseRedirect(reverse('learning_logs:topics', args=()))
    